package com.lnsf.bookstore.web.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.lnsf.bookstore.common.annotation.LoginUser;
import com.lnsf.bookstore.common.controller.ApiBaseAction;
import com.lnsf.bookstore.common.util.CharUtil;
import com.lnsf.bookstore.common.util.MapUtil;
import com.lnsf.bookstore.common.util.PropertyUtil;
import com.lnsf.bookstore.common.util.WechatUtil;
import com.lnsf.bookstore.web.book.service.ApiBookService;
import com.lnsf.bookstore.web.cart.service.ApiCartService;
import com.lnsf.bookstore.web.order.service.ApiOrderService;
import com.lnsf.bookstore.web.order.vo.ApiOrder;
import com.lnsf.bookstore.web.order.vo.WechatRefundApiResult;
import com.lnsf.bookstore.web.orderDetail.service.ApiOrderDetailService;
import com.lnsf.bookstore.web.orderDetail.vo.ApiOrderDetail;
import com.lnsf.bookstore.web.user.vo.ApiUser;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/api/order")
public class ApiOrderController extends ApiBaseAction{

    @Autowired
    private ApiOrderService apiOrderService;

    @Autowired
    private ApiOrderDetailService apiOrderDetailService;

    @Autowired
    private ApiCartService apiCartService;

    @Autowired
    private ApiBookService apiBookService;



    /**
     * 获取订单列表
     */
    @RequestMapping("list")
    public Object list(@LoginUser ApiUser apiUser) {
        JSONObject jsonObject = getJsonRequest();
        Map<String,Object> resultObject = new HashMap<String, Object>();
        Map map = new HashMap();
        map.put("userId",apiUser.getUserId());
        if(jsonObject!=null){
            map.put("orderStatus",jsonObject.get("status"));
            map.put("page",jsonObject.get("page"));
            map.put("limit",jsonObject.get("limit"));
        }

        List<ApiOrder> apiOrderList = apiOrderService.queryList(map);
        resultObject.put("orderList",apiOrderList);
        return toResponsSuccess(resultObject);
    }

    /**
     * 获取订单详情
     */
    @RequestMapping("detail")
    public Object detail(@LoginUser ApiUser loginUser, Integer orderId) {
        Map<String,Object> resultObject = new HashMap<String, Object>();

        ApiOrder apiOrder = apiOrderService.queryObject(orderId);
        if (null == apiOrder) {
            return toResponsObject(400, "订单不存在", "");
        }
        //Map map = new HashMap();
        List<ApiOrderDetail> apiOrderDetailList = apiOrderDetailService.selectDetailByOid(orderId);

        resultObject.put("orderDetailList",apiOrderDetailList);
        resultObject.put("order",apiOrder);
        //下面还有物流接口，快递鸟，暂时还没接入



        return toResponsSuccess(resultObject);
    }
    /**
     * 提交订单
     * @param apiUser
     * @return
     */
    @RequestMapping("submitOrder")
    public Object submitOrder(@LoginUser ApiUser apiUser){
        Map<String,Object> resultObject = new HashMap<String, Object>();

        try {
            resultObject = apiOrderService.submit(getJsonRequest(),apiUser);
            if(resultObject != null){
                return toResponsObject((Integer) resultObject.get("errno"),resultObject.get("errmsg").toString(),resultObject.get("data"));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }


    /**
     * 订单支付,拿到
     * @param apiUser
     * @return
     */
    @RequestMapping("pay")
    public Object pay(@LoginUser ApiUser apiUser, Integer orderId){
        ApiOrder orderInfo = apiOrderService.queryObject(orderId);
        if (null == orderInfo) {
            return toResponsObject(400, "订单已取消", "");
        }
        if (orderInfo.getPayStatus() != 0) {
            return toResponsObject(400, "订单已支付，请不要重复操作", "");
        }
        String nonceStr = CharUtil.getRandomString(32);

        //https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3
        Map<Object, Object> resultObj = new TreeMap();

        try {
            Map<Object, Object> parame = new TreeMap<Object, Object>();
            parame.put("appid", PropertyUtil.getApiProperty("wx.appId"));
            // 商家账号。
            parame.put("mch_id", PropertyUtil.getApiProperty("wx.mchId"));
            String randomStr = CharUtil.getRandomNum(18).toUpperCase();
            // 随机字符串
            parame.put("nonce_str", randomStr);
            // 商户订单编号
            parame.put("out_trade_no", orderId);
            // 商品描述
            parame.put("body", "超市-支付");
            Map orderBooksParam = new HashMap();
            orderBooksParam.put("orderId", orderId);
            //订单的商品
            List<ApiOrderDetail> orderBooks = apiOrderDetailService.queryList(orderBooksParam);
            if (null != orderBooks) {
                String body = "超市-";
                for (ApiOrderDetail apiOrderDetail : orderBooks) {
                    body = body + apiOrderDetail.getApiBook().getName() + "、";
                }
                if (body.length() > 0) {
                    body = body.substring(0, body.length() - 1);
                }
                // 商品描述
                parame.put("body", body);
            }
            //支付金额
            parame.put("total_fee", orderInfo.getActualPrice().multiply(new BigDecimal(100)).intValue());
            // 回调地址
            parame.put("notify_url", PropertyUtil.getApiProperty("wx.notifyUrl"));
            // 交易类型APP
            parame.put("trade_type", PropertyUtil.getApiProperty("wx.tradeType"));
            parame.put("spbill_create_ip", getClientIp());
            parame.put("openid", apiUser.getWeixin_openid());
            String sign = WechatUtil.arraySign(parame, PropertyUtil.getApiProperty("wx.paySignKey"));
            // 数字签证
            parame.put("sign", sign);

            String xml = WechatUtil.convertMap2Xml(parame);
            logger.info("xml:" + xml);
            //下单
            Map<String, Object> resultUn = WechatUtil.xmlStrToMap(WechatUtil.requestOnce(PropertyUtil.getApiProperty("wx.uniformorder"), xml));
            // 响应报文
            String return_code = MapUtil.getString("return_code",resultUn);
            String return_msg = MapUtil.getString("return_msg",resultUn);
            //
            if (return_code.equalsIgnoreCase("FAIL")) {
                return toResponsFail("支付失败," + return_msg);
            } else if (return_code.equalsIgnoreCase("SUCCESS")) {
                // 返回数据
                String result_code = MapUtil.getString("result_code",resultUn);
                String err_code_des = MapUtil.getString("err_code_des",resultUn);
                if (result_code.equalsIgnoreCase("FAIL")) {
                    return toResponsFail("支付失败," + err_code_des);
                } else if (result_code.equalsIgnoreCase("SUCCESS")) {//支付成功
                    String prepay_id = MapUtil.getString("prepay_id",resultUn);
                    // 先生成paySign 参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
                    resultObj.put("appId", PropertyUtil.getApiProperty("wx.appId"));
                    resultObj.put("timeStamp", WechatUtil.timeToStr(System.currentTimeMillis() / 1000, WechatUtil.DATE_TIME_PATTERN));
                    resultObj.put("nonceStr", nonceStr);
                    resultObj.put("package", "prepay_id=" + prepay_id);
                    resultObj.put("signType", "MD5");
                    String paySign = WechatUtil.arraySign(resultObj, PropertyUtil.getApiProperty("wx.paySignKey"));
                    resultObj.put("paySign", paySign);
                    // 业务处理
                    // 付款中
                    orderInfo.setPayStatus(1);
                    apiOrderService.update(orderInfo);
                    return toResponsObject(0, "微信统一订单下单成功", resultObj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("下单失败,error=" + e.getMessage());
        }
        return toResponsFail("下单失败");
    }

    /**
     * 微信订单回调接口
     *
     * @return
     */
    @RequestMapping(value = "/notify", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public void notify(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            InputStream in = request.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.close();
            in.close();
            //xml数据
            String reponseXml = new String(out.toByteArray(), "utf-8");
            WechatRefundApiResult result = (WechatRefundApiResult) WechatUtil.xmlStrToBean(reponseXml, WechatRefundApiResult.class);
            String result_code = result.getResult_code();
            if (result_code.equalsIgnoreCase("FAIL")) {
                //订单编号
                String out_trade_no = result.getOut_trade_no();
                logger.error("订单" + out_trade_no + "支付失败");
                response.getWriter().write(setXml("SUCCESS", "OK"));
            } else if (result_code.equalsIgnoreCase("SUCCESS")) {
                //订单编号
                String out_trade_no = result.getOut_trade_no();
                logger.error("订单" + out_trade_no + "支付成功");
                // 业务处理
                ApiOrder orderInfo = apiOrderService.queryObject(Integer.valueOf(out_trade_no));
                orderInfo.setPayStatus(1);
                orderInfo.setPayTime(new Date());
                if (orderInfo.getOrderStatus() == 0) {
                    orderInfo.setOrderStatus(2);
                }
                apiOrderService.update(orderInfo);
                response.getWriter().write(setXml("SUCCESS", "OK"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }


    /**
     * 获取用户个人中心页面的各订单状态的数字
     * @param apiUser
     * @return
     */
    @RequestMapping("/getTotal4User")
    public Object getTotal(@LoginUser ApiUser apiUser){
        Map<String,Object> resultObject = new HashMap<String, Object>();
        Map params = new HashMap();
        params.put("userId",apiUser.getUserId());
        Map stars = apiOrderService.queryTotal(params);
        resultObject.put("orderCounts",stars);
        return toResponsSuccess(resultObject);
    }

    /**
     * 确认收货
     * @param apiUser
     * @return
     */
    @RequestMapping("/confirm")
    public Object confirm(@LoginUser ApiUser apiUser, Integer orderId){
        Map<String,Object> resultObject = new HashMap<String, Object>();
        try {
            ApiOrder orderVo = apiOrderService.queryObject(orderId);
            orderVo.setOrderStatus(4);
            apiOrderService.update(orderVo);
            return toResponsSuccess("确定收货成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }

    /**
     * 取消订单
     * @param apiUser
     * @return
     */
    @RequestMapping("/revoke")
    public Object revokeOrder(@LoginUser ApiUser apiUser,Integer orderId){
        Map<String,Object> resultObject = new HashMap<String, Object>();
        ApiOrder apiOrder = new ApiOrder();
        apiOrder.setIsCancel(1);
        apiOrder.setId(orderId);
        apiOrderService.update(apiOrder);

        return toResponsMsgSuccess("取消成功");
    }

    /**
     * 订单评论
     * @param apiUser
     * @return
     */
    @RequestMapping("/comment")
    public Object comment(@LoginUser ApiUser apiUser,Integer orderId){
        Map<String,Object> resultObject = new HashMap<String, Object>();

        ApiOrder apiOrder = apiOrderService.queryObject(orderId);
        resultObject.put("order",apiOrder);
        return toResponsSuccess(resultObject);
    }

    //返回微信服务
    public static String setXml(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";
    }

}
